import { Message } from 'element-ui';
import { commonAction } from '@/utils/common'

/**
 * 转换千分位
 * @param number
 * @returns
 */
const reverseNumber = (number: number) => {
  let temp: string = number + '';
  let result: string = ''
  if (temp.length < 3) {
    return temp
  } else {
    while (temp.length > 3) {
      result = ',' + temp.slice(-3) + result
      temp = temp.slice(0, -3)
    }
    result = temp + result
    return result
  }
}

/**
 * try catch封装
 * @param options
 * @param errorWord
 * @param cb
 */
const tryCatchFunc = async (options: any, errorWord: string = '请求失败', cb: (params: any) => void) => {
  try {
    const data = await commonAction(options)
    if (data.success) {
      cb(data)
    } else {
      Message({
        type: 'error',
        message: errorWord
      })
    }
  } catch (e) {
    Message({
      type: 'error',
      message: errorWord
    })
  }
}

/**
 * 触发点击事件
 * @param el
 */
const triggerEvent = (el) => {
  const elem = el.$el
  const evt = document.createEvent('MouseEvents')
  evt.initEvent('click', false, false)
  elem.dispatchEvent(evt)
}

const getTime = (val) => {
  let hour: any = Math.floor(val / 3600)
  hour = hour > 10 ? hour : '0' + hour
  let min: any = Math.floor((val % 3600) / 60)
  min = min > 10 ? min : '0' + min
  let second: any = val % 60
  second = second > 10 ? second : '0' + second
  return hour + ':' + min + ':' + second
}

export {
  reverseNumber,
  tryCatchFunc,
  triggerEvent,
  getTime
}
